package com.fjut.kms.controller;

import com.fjut.kms.domain.User;
import com.fjut.kms.domain.UserActRecord;
import com.fjut.kms.domain.UserLicenseReq;
import com.fjut.kms.exception.KMSException;
import com.fjut.kms.service.*;
import com.fjut.kms.tools.RsaKey;
import com.fjut.kms.tools.TimeHelper;
import com.fjut.kms.tools.XmlManager;

import java.io.BufferedReader;
import java.io.IOException;



/**
 * Created by Empathy on 2017/7/10.
 */
public class ClientServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        //设置响应文件格式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        BufferedReader brReq = request.getReader();
        StringBuffer sResult = new StringBuffer();
        String line = null;
        //char buf[] = new char[300];
        try{
            String xmlStr;
            while ((line = brReq.readLine())!=null){
                sResult.append(line)
                        .append("\n");
            }
            xmlStr=sResult.toString();
            if(xmlStr == null||xmlStr.trim().equals(""))return;

            //HttpSession session=request.getSession();
            RsaKey key = new RsaKey();
            xmlStr = xmlStr.replace("\r","").replace("\n","");
            xmlStr = key.decrypt2(xmlStr);//RSA解密
            xmlStr = java.net.URLDecoder.decode(xmlStr ,"UTF-8");  // 避免中文乱码
            String command = XmlManager.GetFirtElemntByTagName("cmdType",xmlStr);
            String username = XmlManager.GetFirtElemntByTagName("userName",xmlStr);
            String pass = XmlManager.GetFirtElemntByTagName("password",xmlStr);
            UserService userService = new UserServiceImpl();
            User userC = null;
            userC = userService.checkUser(username,pass);
            if("act".equals(command)){
                UserActRecord uar=new UserActRecord();
                uar.setUserName(XmlManager.GetFirtElemntByTagName("userName",xmlStr));
                uar.setSoftName(XmlManager.GetFirtElemntByTagName("softName",xmlStr));
                uar.setReqDate(TimeHelper.getNowTime());
                uar.setStatus(XmlManager.GetFirtElemntByTagName("status",xmlStr));
                uar.setIp(request.getRemoteAddr().toString());
                uar.setMac(XmlManager.GetFirtElemntByTagName("mac",xmlStr));
                uar.setMachineId(XmlManager.GetFirtElemntByTagName("machineId",xmlStr));
                uar.setErrCode(XmlManager.GetFirtElemntByTagName("errCode",xmlStr));
                uar.setOs(XmlManager.GetFirtElemntByTagName("os",xmlStr));
                UserActRecordService uasService=new UserActRecordServiceImpl();
                uasService.add(uar);
                response.getWriter().write("激活信息提交成功！");

            } else if("licenseReq".equals(command)){
                UserLicenseReq ulr=new UserLicenseReq();
                // UserService userService = new UserServiceImpl();

                ulr.setUserName(XmlManager.GetFirtElemntByTagName("userName",xmlStr));
                ulr.setDeptName(userService.getUserDept(ulr.getUserName()));

                ulr.setSoftName(XmlManager.GetFirtElemntByTagName("softName",xmlStr));
                ulr.setReqQuantity(XmlManager.GetFirtElemntByTagName("reqQuantity",xmlStr));
                ulr.setReason(XmlManager.GetFirtElemntByTagName("reason",xmlStr));
                ulr.setReqDate(TimeHelper.getNowTime());
                ulr.setStatus("待审批");
                UserLicenseReqService ulrService=new UserLicenseReqServiceImpl();
                ulrService.add(ulr);
                response.getWriter().write("已申请！");
            }else if("getLicenseReq".equals(command)){
                UserLicenseReqService ulrService=new UserLicenseReqServiceImpl();
                String licenseReqXmlStr=XMLService.generateXMLContents(ulrService.get(username),"com.fjut.kms.domain.UserLicenseReq");
                response.getWriter().write(licenseReqXmlStr);
            }else if ("getActSoftBySoftName".equals(command)){
                UserActRecordService uasService=new UserActRecordServiceImpl();
                String actSoftXmlStr=XMLService.generateXMLContents(uasService.get(username,XmlManager.GetFirtElemntByTagName("softName",xmlStr)),"com.fjut.kms.domain.UserActRecord");
                if(actSoftXmlStr==null) response.getWriter().write("空记录！");
                response.getWriter().write(actSoftXmlStr);
            }else if("getKmsServer".equals(command)){
                SoftWaresService swService=new SoftWaresServiceImpl();
                String resulet=null;
                String wKmsServer=swService.getKmsServerByCategory("windows");
                String oKmsServer=swService.getKmsServerByCategory("office");
                if(wKmsServer!=null) resulet="windows:"+wKmsServer;
                if (oKmsServer!=null) resulet+=";office:"+oKmsServer;
                if (resulet!=null) response.getWriter().write(resulet);
            }
        }catch (KMSException kms){
            String result=XMLService.generateXMLerror(kms.getMessage());
            response.getWriter().write(result);
            System.out.print(kms.getMessage());
        }
        catch (Exception ex){
            String result=XMLService.generateXMLerror(ex.getMessage());
            response.getWriter().write(result);
            System.out.println("error:"+ex.getMessage());
        }


    }



    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        doPost(request,response);
    }
}